package cnhy.salary.service;

import cnhy.salary.domain.AttendanceRecord;
import cnhy.salary.domain.Department;
import cnhy.salary.domain.LeaveRecord;
import cnhy.salary.domain.PostTransfer;
import cnhy.salary.domain.dto.EmployeeDto;
import com.easy.query.api.proxy.base.MapProxy;
import com.easy.query.core.proxy.sql.GroupKeys;
import com.easy.query.core.proxy.sql.Select;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.TreeSelect;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.exception.ServiceException;
import ling.common.EQueryService;
import ling.common.domain.Result;
import lombok.var;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class DepartmentSvc extends EQueryService<Department>{


    Department rootDepartment;
   public Department gotGroupRoot() {
       if(rootDepartment==null)
           rootDepartment= queryHelper.entityQuery(Department.class).where(t -> t.type().eq(10000)).firstOrNull();
       return rootDepartment;
    }

    public List<Long> childrenIds(Long parentId) {
        var list = queryHelper.CreateItems("select dept_id from sys_dept where find_in_set(?, ancestors )", parentId).resultPkg().queryMap();
        var ids = list.stream().map(p -> (Long) p.get("dept_id")).collect(Collectors.toList());
        return ids;
    }
    public List<TreeSelect> treeSelectFilter(Long parentId, List<TreeSelect> deptTree) {

        for (var item : deptTree) {
            if (Objects.equals(item.getId(),parentId))
                return item.getChildren();
            var re = treeSelectFilter(parentId,item.getChildren());
            if (re != null)
                return re;
        }
        return null;
    }
    public int insertDept(Department dept) {
        Department info = queryHelper.entityQuery(Department.class).whereById(dept.getParentId()).firstOrNull();
        // 如果父节点不为正常状态,则不允许新增子节点
        if (!UserConstants.DEPT_NORMAL.equals(info.getStatus())) {
            throw new ServiceException("部门停用，不允许新增");
        }
        dept.setAncestors(info.getAncestors() + "," + dept.getParentId());
        return (int)queryHelper.query().insertable(dept).executeRows(true);
    }

    /** 按部门统计：all部门总数，leave请假数，kq0正常、1迟到、2缺卡、10补卡
     *
     * @param deptId
     * @return
     */
    public LinkedHashMap<String,Long> statEmpl(Long deptId, Date begin,Date end){

       //员工，出勤，调岗通知；应到，实到，请假，迟到，实到=请假+迟到+正常
        var all= queryHelper.queryable(EmployeeDto.class)
                 .where(p->p.eq(EmployeeDto::getDeptId,deptId)).count();
         var countList=queryHelper.entityQuery(AttendanceRecord.class)
                 .where(a -> a.deptId().eq(deptId))
                 .where(a -> a.dayDate().rangeOpen(begin,end))
                 .groupBy(a -> GroupKeys.of(a.resultExt()))
                 .select(group -> Select.DRAFT.of(group.key1(),group.count())).toList();
        var leaveCount=queryHelper.entityQuery(LeaveRecord.class)
                .where(p->p.deptId().eq(deptId))
                .where(l -> l.status().eq(100))
                .where(a -> a.beginTime().rangeOpen(begin,end))
                .groupBy(l -> GroupKeys.of(l.userId()))
                .count();

        var map=new LinkedHashMap<String,Long>();
        map.put("all",all);
        map.put("leave",leaveCount);
        countList.forEach(p->map.put("kq"+p.getValue1(),p.getValue2()));
        return  map;
    }
}
